package com.data.modules.health.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.data.common.api.vo.Result;
import com.data.common.aspect.annotation.AutoLog;
import com.data.common.system.query.QueryGenerator;
import com.data.common.system.vo.LoginUser;
import com.data.modules.health.entity.HlContactsInfo;
import com.data.modules.health.entity.HlUser;
import com.data.modules.health.entity.HlUserBed;
import com.data.modules.health.entity.HlUserHealth;
import com.data.modules.health.service.IHlContactsInfoService;
import com.data.modules.health.service.IHlUserBedService;
import com.data.modules.health.service.IHlUserHealthService;
import com.data.modules.health.service.IHlUserService;
import com.data.modules.health.vo.HlUserPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: 老人档案信息
 * @Author: data-boot
 * @Date:   2023-07-17
 * @Version: V1.0
 */
@Api(tags="老人档案信息")
@RestController
@RequestMapping("/health/hlUser")
@Slf4j
public class HlUserController {

	@Autowired
	private IHlUserService hlUserService;
	@Autowired
	private IHlContactsInfoService hlContactsInfoService;
	@Autowired
	private IHlUserHealthService hlUserHealthService;

	 @Autowired
	 private IHlUserBedService hlUserBedService;

	 /**
	  * 分页列表查询
	  *
	  * @param hlUser
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @ApiOperation(value="老人档案信息-分页列表查询", notes="老人档案信息-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<?> queryPageList(HlUser hlUser,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<HlUser> queryWrapper = QueryGenerator.initQueryWrapper(hlUser, req.getParameterMap());
		 Page<HlUser> page = new Page<HlUser>(pageNo, pageSize);
		 IPage<HlUser> pageList = hlUserService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  *   添加
	  *
	  * @param hlUserPage
	  * @return
	  */
	 @ApiOperation(value="老人档案信息-添加", notes="老人档案信息-添加")
	 @PostMapping(value = "/add")
	 public Result<?> add(@RequestBody HlUserPage hlUserPage) {
		 HlUser hlUser = new HlUser();
		 BeanUtils.copyProperties(hlUserPage, hlUser);
		 hlUserService.saveMain(hlUser, hlUserPage.getHlContactsInfoList(),hlUserPage.getHlUserHealthList(),hlUserPage.getHlUserBedList());
		 return Result.OK("添加成功！");
	 }

	 /**
	  *  编辑
	  *
	  * @param hlUserPage
	  * @return
	  */
	 @ApiOperation(value="老人档案信息-编辑", notes="老人档案信息-编辑")
	 @PutMapping(value = "/edit")
	 public Result<?> edit(@RequestBody HlUserPage hlUserPage) {
		 HlUser hlUser = new HlUser();
		 BeanUtils.copyProperties(hlUserPage, hlUser);
		 HlUser hlUserEntity = hlUserService.getById(hlUser.getId());
		 if(hlUserEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 hlUserService.updateMain(hlUser, hlUserPage.getHlContactsInfoList(),hlUserPage.getHlUserHealthList(),hlUserPage.getHlUserBedList());
		 return Result.OK("编辑成功!");
	 }

	 /**
	  *   通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="老人档案信息-通过id删除", notes="老人档案信息-通过id删除")
	 @DeleteMapping(value = "/delete")
	 public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		 hlUserService.delMain(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  *  批量删除
	  *
	  * @param ids
	  * @return
	  */
	 @ApiOperation(value="老人档案信息-批量删除", notes="老人档案信息-批量删除")
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		 this.hlUserService.delBatchMain(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功！");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="老人档案信息-通过id查询", notes="老人档案信息-通过id查询")
	 @GetMapping(value = "/queryById")
	 public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		 HlUser hlUser = hlUserService.getById(id);
		 if(hlUser==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(hlUser);

	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="联系人信息主表ID查询", notes="联系人信息-通主表ID查询")
	 @GetMapping(value = "/queryHlContactsInfoByMainId")
	 public Result<?> queryHlContactsInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<HlContactsInfo> hlContactsInfoList = hlContactsInfoService.selectByMainId(id);
		 return Result.OK(hlContactsInfoList);
	 }
	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="健康信息主表ID查询", notes="健康信息-通主表ID查询")
	 @GetMapping(value = "/queryHlUserHealthByMainId")
	 public Result<?> queryHlUserHealthListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<HlUserHealth> hlUserHealthList = hlUserHealthService.selectByMainId(id);
		 return Result.OK(hlUserHealthList);
	 }
	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="老人床位信息主表ID查询", notes="老人床位信息-通主表ID查询")
	 @GetMapping(value = "/queryHlUserBedByMainId")
	 public Result<?> queryHlUserBedListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<HlUserBed> hlUserBedList = hlUserBedService.selectByMainId(id);
		 return Result.OK(hlUserBedList);
	 }

	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param hlUser
	  */
	 @RequestMapping(value = "/exportXls")
	 public ModelAndView exportXls(HttpServletRequest request, HlUser hlUser) {
		 // Step.1 组装查询条件查询数据
		 QueryWrapper<HlUser> queryWrapper = QueryGenerator.initQueryWrapper(hlUser, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 //Step.2 获取导出数据
		 List<HlUser> queryList = hlUserService.list(queryWrapper);
		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 List<HlUser> hlUserList = new ArrayList<HlUser>();
		 if(ObjectUtil.isEmpty(selections)) {
			 hlUserList = queryList;
		 }else {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 hlUserList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 }

		 // Step.3 组装pageList
		 List<HlUserPage> pageList = new ArrayList<HlUserPage>();
		 for (HlUser main : hlUserList) {
			 HlUserPage vo = new HlUserPage();
			 BeanUtils.copyProperties(main, vo);
			 List<HlContactsInfo> hlContactsInfoList = hlContactsInfoService.selectByMainId(main.getId());
			 vo.setHlContactsInfoList(hlContactsInfoList);
			 List<HlUserHealth> hlUserHealthList = hlUserHealthService.selectByMainId(main.getId());
			 vo.setHlUserHealthList(hlUserHealthList);
			 List<HlUserBed> hlUserBedList = hlUserBedService.selectByMainId(main.getId());
			 vo.setHlUserBedList(hlUserBedList);
			 pageList.add(vo);
		 }

		 // Step.4 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "老人档案信息列表");
		 mv.addObject(NormalExcelConstants.CLASS, HlUserPage.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("老人档案信息数据", "导出人:"+sysUser.getRealname(), "老人档案信息"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		 return mv;
	 }

	 /**
	  * 通过excel导入数据
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<HlUserPage> list = ExcelImportUtil.importExcel(file.getInputStream(), HlUserPage.class, params);
				 for (HlUserPage page : list) {
					 HlUser po = new HlUser();
					 BeanUtils.copyProperties(page, po);
					 hlUserService.saveMain(po, page.getHlContactsInfoList(),page.getHlUserHealthList(),page.getHlUserBedList());
				 }
				 return Result.OK("文件导入成功！数据行数:" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(),e);
				 return Result.error("文件导入失败:"+e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.OK("文件导入失败！");
	 }


 }
